package Server;

/**
 *
 * @author Daniel
 */
import java.net.*;
import java.io.*;

public class Server
{
    //Holds the server port
    private ServerSocket connection = null;
    //Clients ID
    private int clients             = 0;
    
    //Server constructor, must specify a port number!!
    public Server(int port)
    {
        //Construct
        System.out.println("Attempting to initialize server...");
        
        //Try to create the server socket, then print out the server address
        try
        {
            this.connection    = new ServerSocket(port);
            System.out.println("I am: " + this.connection.getInetAddress());
        }
        catch(Exception e)
        {
            System.out.println("Server init failed.");
            System.out.println("Error: " + e);
            System.exit(1);
        }
        
        //Confirmation that server interface is up
        System.out.println("Server up");
    }
    
    //Listen method, continuous loop to create new Client objects
    public void listen()
    {
        System.out.println("Listening...");
        
        //Continously loop
        //TODO: add the ability to escape and cleanly terminate program
        while(true)
        {
            try
            {
                //Create a new client object, pass the incoming connection and client count
                Client client = new Client(this.connection.accept(), clients++);
                //We want to print out where the connection came from
                System.out.println(client.getSocket().getLocalAddress().getHostName() + " connected");
                //Listening again
                System.out.println("Listening...");
            }
            catch(IOException ioe)
            {
                System.out.println("Error accepting client.");
                System.out.println("Error: " + ioe);
                System.exit(2);
            }
        }
    }
}
